module Mongowiki
  class Wikipage
    attr_accessor :title, :url, :keywords, :links, :citations
    attr_reader :dbname, :host, :port
    
    DEFAULT_DBNAME = 'specdb'
    DEFAULT_HOST   = 'localhost'
    DEFAULT_PORT   = 27017
    
    def self.import(pagelist, *conn)
      connect(*conn) do |pages|
        pagelist.each do |pg|
          pages.insert(:title     => pg.title,
                       :url       => pg.url,
                       :keywords  => pg.keywords,
                       :links     => pg.links,
                       :citations => pg.citations)
        end
      end
    end

    def self.find_one(*conn)
      connect(*conn) do |pages|
        pages.find_one
      end
    end
    
    def self.find(criteria={}, *conn)
      connect(*conn) { |pages| pages.find(criteria) }
    end
    
    def self.index_on(field, *conn)
      connect(*conn) { |pages| pages.create_index(field) }
    end
    
    def initialize(info={}, *conn)
      @dbname = conn[0] || DEFAULT_DBNAME
      @host   = conn[1] || DEFAULT_HOST
      @port   = conn[2] || DEFAULT_PORT
      
      @title     = info[:title]     || ''
      @url       = info[:url]       || ''
      @keywords  = info[:keywords]  || []
      @links     = info[:links]     || []
      @citations = info[:citations] || []
    end
    
    def save
      Wikipage.connect(@dbname, @host, @port) do |pages|
        pages.insert(:title     => @title,
                     :url       => @url,
                     :keywords  => @keywords,
                     :links     => @links,
                     :citations => @citations)
      end
    end

    
    private
    
    def self.connect(*conn)
      dbname = conn[0] || DEFAULT_DBNAME
      host   = conn[1] || DEFAULT_HOST
      port   = conn[2] || DEFAULT_PORT
      
      conn = Mongo::Connection.new(host, port)
      pages = conn.db(dbname).collection('pages')
      
      begin
        yield(pages)
      ensure
        conn.close
      end
    end

  end
end